import { _decorator, Component, Sprite, SpriteAtlas } from 'cc';
import { createNode, GCTDBoard } from './Common';
import { GridForm, KKP2DTable } from '@coldcloude/kakera';
import { GCTD_CFG_UI } from './Constant';
import { NodeEx } from './lib/kakera-cocos/scripts/NodeEx';
const { ccclass, property } = _decorator;

@ccclass('BattleBoardController')
export class BattleBoardController extends Component {

    board:GCTDBoard;

    gridForm:GridForm;

    atlas:SpriteAtlas;

    spriteNodeMap = new KKP2DTable<NodeEx>();
    spriteMap = new KKP2DTable<Sprite>();

    init() {
        for(let y=0; y<this.board.size.height; y++){
            for(let x=0; x<this.board.size.width; x++){
                const pos = {x:x,y:y};
                const nn = createNode();
                this.node.addChild(nn);
                this.spriteNodeMap.set(pos,nn);
                const sprite = nn.addComponent(Sprite);
                this.spriteMap.set(pos,sprite);
                const pp = this.gridForm.toPixel(pos);
                nn.setPosition(pp.x,pp.y);
            }
        }
    }

    render(dt:number) {
        this.spriteMap.foreach((pos,sprite)=>{
            const v = this.board.getP(pos);
            const sn = GCTD_CFG_UI.block.sprites[v];
            sprite.spriteFrame = this.atlas.getSpriteFrame(sn);
        });
    }
}


